import { isEmpty, isEmptys } from '../validate'

/** @name Bus 消息通信 */
export default class BusMessage {

  /** 生成一个 Bus 消息通讯 */
  static init() {
    return new BusMessage();
  }
  
  /** 工具语义化 */
  static absorb(bus){
	  return bus
  }

  // 消息队列
  list = []

  /** 消息订阅 */
  subscribe(key, callback, routeid) {
    if(isEmptys([key, callback])) return;
    this.list.push({ key, callback, routeid })
  }

  /** 发布消息 */
  publish(key, data, routeid) {
    if(isEmpty(key)) return;
    this.list.filter(item => item.key === key).forEach(item => {
      if(isEmpty(routeid) || item.routeid === routeid){
		item.callback(data);
      }
    })
  }

  /** 移除订阅消息 */
  remove(key, routeid) {
	const _list = this.list.filter(item => {
      if (isEmpty(routeid)) {
        return item.key !== key;
      }
	  
      return item.routeid !== routeid;
    })
	
	//console.log('_list', _list)
    this.list = _list
  }
}